﻿#include "clockfragment.h"
#include "ui_clockfragment.h"
#include "loader.h"
#include "clockitemfragment.h"
#include "getclockeventdialog.h"
#include <QMessageBox>
#include <QDebug>
#include <QCalendar>
ClockFragment::ClockFragment(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ClockFragment) {
    ui->setupUi(this);
    QVector<Clock> clocks = Loader::loadClocks("./savings/clock_items.json");
    for(auto &x:clocks) {
        this->clocks[x.getName()] = x;
    }
    layout = new QGridLayout(ui->scrollArea);
    for(auto &x:clocks) {
        ClockItemFragment *fragment = new ClockItemFragment(x);
        fragment->setMinimumSize(QSize(fragment->geometry().width(),fragment->geometry().height()));
        layout->addWidget(fragment);
    }
    connect(&timer,&QTimer::timeout,this,&ClockFragment::timeout);
    timer.setInterval(300);
    timer.start();
    ui->scrollArea->widget()->setLayout(layout);
}

ClockFragment::~ClockFragment() {
    delete layout;
    delete ui;

}

void ClockFragment::on_pushButton_clicked() {
    Clock clock = GetClockEventDialog::getClock();
    if(clock.getName()=="")return;
    this->clocks[clock.getName()] = clock;
    layout->addWidget(new ClockItemFragment(clock));
    QVector<Clock> es;
    for(auto &x:clocks.values())es.append(x);
    Loader::saveClock(es,"./savings/clock_items.json");
}

void ClockFragment::timeout() {
    ui->label_showtime->setText(QTime::currentTime().toString("hh:mm"));
    int timeStamp = QTime::currentTime().msecsSinceStartOfDay();
    QCalendar calendar;
    for(auto &x:clocks.values()) {
        int eventstamp = x.getTime().msecsSinceStartOfDay();
        if(timeStamp>=eventstamp&&timeStamp<=eventstamp+20&&!showed.contains(x.getName())&&(x.getRepeat()&(1<<calendar.dayOfWeek(QDate::currentDate())))) {
            showed[x.getName()] = true;
            tts.say(tr("time's up:")+x.getName());
            QMessageBox::information(this,tr("Time out"),tr("time's up:")+x.getName());

        }
    }
}

void ClockFragment::on_pushButton_2_clicked() {
    for(int i = 0; i<clocks.count(); i++) {
        QLayoutItem* pLayout = layout->itemAt(i);
        ClockItemFragment *frag = (ClockItemFragment*)pLayout->widget();
        if(frag->isChosen()) {
            clocks.remove(frag->getClock().getName());
            frag->deleteLater();
        }
    }
    QVector<Clock> updated;
    for(auto &x:clocks.values())updated.append(x);
    Loader::saveClock(updated,"./savings/clock_items.json");
}
